package edu.clarkson.ee368.spring2012.coreservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@ClientLogin
public class ClientLoginAuthenticator implements GoogleServiceAuthenticator {

	private static final String CLIENT_LOGIN_URL = "https://www.google.com/accounts/ClientLogin";;

	@Override
	public void authenticate(HostedApplication hostedApplication, String email, String password) {

		String authToken = null;
		// Assemble request
		StringBuilder builder = new StringBuilder();
		builder.append("Email=").append(email);
		builder.append("&Passwd=").append(password);
		builder.append("&accountType=GOOGLE");
		builder.append("&source=").append(hostedApplication);
		builder.append("&service=").append("ac2dm");
		byte[] data = builder.toString().getBytes();

		try {

			URL url = new URL(CLIENT_LOGIN_URL);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setUseCaches(false);
			con.setDoOutput(true);
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			con.setRequestProperty("Content-Length",
					Integer.toString(data.length));

			// Issue the HTTP POST request
			OutputStream output = con.getOutputStream();
			output.write(data);
			output.close();

			// Read the response
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line.startsWith("Auth=")) {
					authToken = line.split("=")[1];
				}
			}

		} catch (Exception e) {
			// Authentication Exception
			e.printStackTrace();
		}

		hostedApplication.setC2DMAuthenticationToken(authToken);

	}

	@Override
	public void applyAuthenticationToHttpConnection(
			HostedApplication hostedApplication, String service,
			HttpURLConnection connection)
			throws GoogleServiceAuthenticationException {
		String authToken = hostedApplication.getC2DMAuthenticationToken();
		if (authToken == null) {
			throw new GoogleServiceAuthenticationException();
		}
		connection.setRequestProperty("Authentication", "GoogleLogin auth="
				+ authToken);
	}

	@Override
	public void ensureAuthenticationWasAccepted(HttpURLConnection connection)
			throws GoogleServiceAuthenticationException {
		int responseCode = 0;
		try {
			responseCode = connection.getResponseCode();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (responseCode == 401) { // Need to refresh our auth token
			throw new GoogleServiceAuthenticationException();
		}
	}

}
